package org.com.mars.controller.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.com.fw.util.StringUtil;
import org.springframework.ui.Model;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ControllerUtil {
	
	/**
	 * 根据json信息，List<DTO>
	 *
	 * @param jsonStr
	 *            json
	 * @param clazz
	 *            Dto类
	 * @return 返回List<DTO>
	 */
	public static List<?> jsonToList(String jsonStr, Class<?> clazz) {
		JSONArray arr = JSONArray.fromObject(jsonStr);
		List<?> list = (List<?>) JSONArray.toCollection(arr, clazz);
		return list;
	}
	
	/**
	 * 根据Object数据，转成json信息。
	 *
	 * @param jsonStr
	 *            json
	 * @param clazz
	 *            Dto类
	 * @return 返回List<DTO>
	 */
	public static String toJson(Object object) {
		JSONObject jobj = JSONObject.fromObject(object);
		return jobj.toString();
	}

	/**
	 * 非同期返回
	 *
	 * @param response
	 * @param json
	 * @throws IOException
	 */
	public static void sendJsonToResult(HttpServletResponse response,
			Map<String, Object> json) throws IOException {
		JSONObject resultObj = JSONObject.fromObject(json);
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(resultObj.toString());
	}
	
	/**
	 * 取得jsp路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getControllerRetrun(HttpServletRequest request) {
		String returnString = "";
		// 请求URL
		String url = request.getRequestURI().trim();
		String contextPath = request.getContextPath();
		if (StringUtil.isEmpty(contextPath)) {
			returnString = url;
		} else if (StringUtil.isEmpty(url)) {
			returnString = "";
		} else if (url.startsWith(contextPath)) {
			returnString = url.replaceFirst(contextPath, "");
			returnString = returnString.substring(0, returnString.indexOf("."));
		}
		return returnString;
	}
}
